<template>
  <el-row :gutter="10">
    <el-col :span="12">
      <el-input placeholder="请输入文章标题" v-model="titleValue"></el-input>
    </el-col>
    <el-col :span="12">
      <el-button type="primary" @click="handleSubmitClick">发布</el-button>
    </el-col>
  </el-row>
  <div class="editor-area" style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup>
import { computed, watch } from "vue"
import { useStore } from "vuex"
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { getWeblog, editWeblog } from "../../service/api_weblog"
// 页面数据
const props = defineProps({
  weblogId: {
    type: String,
    default: null
  }
})
const store = useStore()
const flag = computed(() => store.state.weblog.flag)
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 内容 HTML
const valueHtml = ref("");
// 文章标题
const titleValue = ref("");

watch(flag, () => {
  valueHtml.value = ""
  titleValue.value = ""
})

// 工具栏配置
const toolbarConfig = {};
// 编辑器配置
const editorConfig = { placeholder: "请输入内容..." };

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
// 简洁模式
const mode = "default";
const emit = defineEmits(["release"]);

// 事件处理
// 发布按钮点击
const handleSubmitClick = () => {
  if (!titleValue.value.length) return ElMessage.error("发布失败, 文章标题不能为空!")
  if (valueHtml.value === "<p><br></p>") return ElMessage.error("发布失败, 文章内容不能为空!")
  if (props.weblogId) {
    editWeblog(props.weblogId, titleValue.value, valueHtml.value).then(res => {
      if (res.status === 200) {
        ElMessage.success("更新文章成功")
        store.commit("weblog/changeWeblogFlagMutation")
      }
    })
  } else {
    emit("release", { title: titleValue.value, content: valueHtml.value })
  }
}

// 生命周期
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

// 网络请求
getWeblog(props.weblogId).then(res => {
  const { title, content } = res.data
  valueHtml.value = content
  titleValue.value = title
})
</script>

<style scoped>
.editor-area {
  z-index: 1001;
}
.el-row {
  margin-bottom: 20px;
}
</style>
